package com.epfresh.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.epfresh.R;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.SearchBean;
import com.epfresh.bean.VoiceResult;
import com.epfresh.global.BaseActivity;
import com.epfresh.views.tag.FlowLayout;
import com.epfresh.views.tag.TagAdapter;
import com.epfresh.views.tag.TagFlowLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

public class SearchActivity extends BaseActivity implements EventListener {

    static final String TAG = "SearchActivity";
    ImageView ivBack;
    ImageView ivSearch;
    EditText etContent;
    TextView tvSearch;
    ImageView ivDelete;
    View llHot, rlHistory, rlAutomatic;
    HorizontalScrollView hsvHot;
    ListView lvAutomatic;
    TextView tvAutomatic;
    SearchAdapter historyAdapter;
    StringAdapter autoAdapter;
    String historyTogether;

    ArrayList<String> hotList = new ArrayList<>();
    ArrayList<String> autoList = new ArrayList<>();
    InputMethodManager inputMethodManager;

    ArrayList<SearchBean> beanList;

    private TagFlowLayout fl_tags;
    private TagAdapter<SearchBean> tagAdapter;
    private String marketId;
    private ImageView img_clear_search;


    private View rl_tips;
    private ImageView img_voice_identify;
    private TextView txt_tip1, txt_tip2, txt_tip3, txt_tip4, txt_tip5;
    private GifImageView img_gif_voice;
    private TextView txt_voice_search;
    private ImageView img_cancel;

    private boolean isVoiceRunning = false;
    private boolean haveRecording = false;
    private boolean activeShutdown = false;
    private EventManager asr;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        marketId = getIntent().getStringExtra("marketId");
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        initVoiceConfigure();
        inputMethodManager.showSoftInput(etContent, InputMethodManager.SHOW_FORCED);
    }

    @Override
    protected void onResume() {
        super.onResume();
        beanList = getHistory();
//        historyAdapter = new SearchAdapter(this, beanList, R.layout.item_string);
//        lvHistory.setAdapter(historyAdapter);
//        historyAdapter.notifyDataSetChanged();

        tagAdapter = new TagAdapter<SearchBean>(beanList) {
            @Override
            public View getView(FlowLayout parent, int position, SearchBean searchBean) {
                TextView historyTag = (TextView) LayoutInflater.from(SearchActivity.this).inflate(R.layout.history_tag, parent, false);
                if (searchBean.getType() == 1) {
                    historyTag.setText(searchBean.getContent());
                } else {
                    historyTag.setText("\"" + searchBean.getContent() + "\"" + "店铺");
                }
                return historyTag;
            }
        };

        fl_tags.setAdapter(tagAdapter);
        tagAdapter.notifyDataChanged();
    }


    private void initView() {
        setContentView(R.layout.activity_search);
        hsvHot = (HorizontalScrollView) findViewById(R.id.hsv_hot);
        requestHot();
        llHot = findViewById(R.id.ll_hot);
        rlHistory = findViewById(R.id.rl_history);
        rlAutomatic = findViewById(R.id.rl_automatic);
        tvAutomatic = (TextView) findViewById(R.id.tv_automatic);
//        lvHistory = (ListView) findViewById(R.id.lv_history);
        autoAdapter = new StringAdapter(this, autoList, R.layout.item_string);
        lvAutomatic = (ListView) findViewById(R.id.lv_automatic);
        lvAutomatic.setAdapter(autoAdapter);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        etContent = (EditText) findViewById(R.id.et_content);
        tvSearch = (TextView) findViewById(R.id.tv_search);
        img_clear_search = findViewById(R.id.img_clear_search);
        img_clear_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etContent.setText("");
            }
        });
        tvAutomatic.setOnClickListener(this);
        tvSearch.setOnClickListener(this);
        ivDelete = (ImageView) findViewById(R.id.iv_delete);
        ivDelete.setOnClickListener(this);
        ivBack.setOnClickListener(this);

        rl_tips = findViewById(R.id.rl_tips);
        img_voice_identify = findViewById(R.id.img_voice_identify);
        txt_tip1 = findViewById(R.id.txt_tip1);
        txt_tip2 = findViewById(R.id.txt_tip2);
        txt_tip3 = findViewById(R.id.txt_tip3);
        txt_tip4 = findViewById(R.id.txt_tip4);
        txt_tip5 = findViewById(R.id.txt_tip5);
        img_gif_voice = findViewById(R.id.img_gif_voice);
        txt_voice_search = findViewById(R.id.txt_voice_search);
        img_cancel = findViewById(R.id.img_cancel);

        txt_voice_search.setOnClickListener(this);
        img_cancel.setOnClickListener(this);

        fl_tags = findViewById(R.id.fl_tags);
        fl_tags.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                SearchBean searchBean = beanList.get(position);
                if (searchBean.getType() == 1) {
                    etContent.setText(searchBean.getContent());
                    etContent.setSelection(searchBean.getContent().length());
                    tvSearch.performClick();
                } else {
                    etContent.setText(searchBean.getContent());
                    etContent.setSelection(searchBean.getContent().length());
                    tvAutomatic.performClick();
                }
                return true;
            }
        });

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(etContent.getText())) {
                    img_clear_search.setVisibility(View.INVISIBLE);
                    llHot.setVisibility(View.VISIBLE);
                    rlHistory.setVisibility(View.VISIBLE);
                    rlAutomatic.setVisibility(View.GONE);
                    tagAdapter.notifyDataChanged();
                } else {
                    img_clear_search.setVisibility(View.VISIBLE);
                    llHot.setVisibility(View.GONE);
                    rlHistory.setVisibility(View.GONE);
                    rlAutomatic.setVisibility(View.VISIBLE);
                    requestAuto();
                }
            }
        });

        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    if (TextUtils.isEmpty(etContent.getText().toString())) {
                        return true;
                    }
                    if (!VerificationUtils.isValid(etContent.getText().toString())) {
                        toast("请删除特殊字符");
                        return true;
                    }
                    Intent goodsList = new Intent(SearchActivity.this, SearchResultActivity.class);
                    goodsList.putExtra("title", etContent.getText().toString());
                    goodsList.putExtra("marketId", marketId);
                    startActivity(goodsList);
//                    Intent goodsList = new Intent(SearchActivity.this, GoodsListActivity.class);
//                    goodsList.putExtra("title", etContent.getText().toString());
//                    goodsList.putExtra("type_view", 2);
//                    startActivity(goodsList);
                    inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                    addHistory(1, etContent.getText().toString());
                    return true;
                }
                return false;
            }
        });
    }

    void initHot() {
        LinearLayout llHotContent = (LinearLayout) findViewById(R.id.ll_hot_content);
        int roundRadius = 15; // 8px not dp
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        for (int i = 0; i < hotList.size(); i++) {
            TextView flag = new TextView(this);
            flag.setText(hotList.get(i));
            flag.setTextSize(12);
            flag.setTag(hotList.get(i));
            flag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    etContent.setText(v.getTag().toString());
                    etContent.setSelection(v.getTag().toString().length());
                    tvSearch.performClick();
                }
            });
            GradientDrawable gd = (GradientDrawable) getResources().getDrawable(R.drawable.btn_hot_search);
//            gd.setCornerRadius(roundRadius);
            lp.setMargins(10, 0, 10, 0);
            flag.setLayoutParams(lp);
            flag.setBackgroundDrawable(gd);
            llHotContent.addView(flag);
        }
    }

    protected View getToolBar() {
        View actionbar = this.inflaterView(R.layout.toolbar_search_goods_store, null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, this.getResources().getDimensionPixelSize(com.epfresh.api.R.dimen.action_bar_height));
        actionbar.setLayoutParams(lp);
        return actionbar;
    }

    @Override
    protected void onToolbarBack() {
        inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
        super.onToolbarBack();
    }

/*    public static void onEvent(Context context, String id, HashMap<String,String> m, long value){
        m.put("__ct__", String.valueOf(value));
        MobclickAgent.onEvent(context, id, m);
    }*/

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                // 返回上一页
                inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                finish();
                break;
            case R.id.tv_search:
                // 搜商品
                if (TextUtils.isEmpty(etContent.getText().toString())) {
                    return;
                }

                HashMap<String, String> test_new = new HashMap<>();
                test_new.put("map_new_key_1" + getUser().getAccountId(), etContent.getText().toString() + "map_value_0001");
                test_new.put("map_new_key_2" + getUser().getAccountId(), etContent.getText().toString() + "map_value_0002");

                MobclickAgent.onEventValue(this, "purchaser_search_goods", test_new, 1);

/*                HashMap<String , String> test_old = new HashMap<>();
                test_old.put("map_old_key_1"+getUser().getAccountId(),etContent.getText().toString()+"map_value_0001");
                test_old.put("map_old_key_2"+getUser().getAccountId(),etContent.getText().toString()+"map_value_0002");

                onEvent(this, "purchaser_search_goods", test_old,100);*/

                if (!VerificationUtils.isValid(etContent.getText().toString())) {
                    toast("请删除特殊字符");
                    return;
                }
//                Intent goodsList = new Intent(this, GoodsListActivity.class);
                Intent goodsList = new Intent(this, SearchResultActivity.class);
                goodsList.putExtra("title", etContent.getText().toString());
                goodsList.putExtra("marketId", marketId);
//                goodsList.putExtra("type_view", 2);
                startActivity(goodsList);
                inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                addHistory(1, etContent.getText().toString());
                //historyAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_automatic:
                // 搜店铺
//                Intent storesList = new Intent(this, SearchStoreActivity.class);
                Intent storesList = new Intent(this, SearchResultActivity.class);
                storesList.putExtra("searchKey", etContent.getText().toString());
                storesList.putExtra("marketId", marketId);
                storesList.putExtra("store", "store");
                startActivity(storesList);
                addHistory(0, etContent.getText().toString());
                inputMethodManager.hideSoftInputFromWindow(etContent.getWindowToken(), 0);
                //historyAdapter.notifyDataSetChanged();
                break;
            case R.id.iv_delete:

                CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                builder.setMessage("确定要删除搜索历史吗？");//设置显示的内容
                //builder.setTitle("提示");
                builder.setTitleVisible(false);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        beanList.clear();
//                        historyAdapter.notifyDataSetChanged();
                        tagAdapter.notifyDataChanged();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件
                        dialog.dismiss();
                    }

                });
                builder.create().show();
                break;
            case R.id.txt_voice_search:
                if (!isVoiceRunning) {
                    audioPermissionCheck();
                } else {
                    activeShutdown = true;
                    voiceActiveStop();
                }
                break;

            case R.id.img_cancel:
                voiceCancel();
                break;
            default:
                break;
        }
    }

    void addHistory(int type, String content) {
        for (int i = 0; i < beanList.size(); i++) {
            if (beanList.get(i).getType() == type) {
                if (beanList.get(i).getContent().equals(content)) {
                    beanList.remove(i);
                    break;
                }
            }
        }
        beanList.add(0, new SearchBean(type, content));
    }

    class StringAdapter extends CommonAdapter<String> {
        public StringAdapter(Context context, List<String> historyList, int a) {
            super(context, historyList, a);
        }

        @Override
        public void convert(ViewHolder holder, final String bean) {
            holder.setText(R.id.tv_string, bean);
            holder.setOnClickListener(R.id.tv_string, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    etContent.setText(bean);
                    etContent.setSelection(bean.length());
                    tvSearch.performClick();
                }
            });
        }
    }


    class SearchAdapter extends CommonAdapter<SearchBean> {
        public SearchAdapter(Context context, List<SearchBean> historyList, int a) {
            super(context, historyList, a);
        }

        @Override
        public int getCount() {
            if (mDatas == null) {
                return 0;
            }
            if (mDatas.size() < 10)
                return mDatas.size();
            else
                return 10;
        }

        @Override
        public void convert(ViewHolder holder, final SearchBean bean) {
            if (bean.getType() == 1) {
                holder.setText(R.id.tv_string, bean.getContent());
                holder.setOnClickListener(R.id.tv_string, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        etContent.setText(bean.getContent());
                        etContent.setSelection(bean.getContent().length());
                        tvSearch.performClick();
                    }
                });
            } else {
                holder.setText(R.id.tv_string, "\"" + bean.getContent() + "\"" + "店铺");
                holder.setOnClickListener(R.id.tv_string, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        etContent.setText(bean.getContent());
                        etContent.setSelection(bean.getContent().length());
                        tvAutomatic.performClick();
                    }
                });
            }
        }
    }

    public void requestHot() {
        final RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_search_hot);
        requestEntity.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        request(requestEntity, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_search_hot, new OnRequestListener<ArrayList<String>>() {
            @Override
            public ArrayList<String> jsonToObj(String s) {
                return new Gson().fromJson(s,
                        new TypeToken<ArrayList<String>>() {
                        }.getType());
            }

            @Override
            public void onFail(int i, Object o, Object o1) {
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int i, Object o, Object o1) {
                hideProgressDialog();
            }

            @Override
            public void onStart(Object o) {
                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<ArrayList<String>> responseEntity, Object o) {
                hideProgressDialog();
                hotList.addAll(responseEntity.getResponseElement());
                if (hotList.size() > 0) {
                    llHot.setVisibility(View.VISIBLE);
                    initHot();
                } else {
                    llHot.setVisibility(View.GONE);
                }

            }
        });
    }

    public void requestAuto() {
        final RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_product_autoComplete);
        requestEntity.putParameter("keyword", etContent.getText().toString());
        RequestTag requestTag = new RequestTag();
        requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_product_autoComplete;
        requestTag.type = RequestTag.TYPE_CURRENT;
        request(requestEntity, requestTag, new OnRequestListener<ArrayList<String>>() {
            @Override
            public ArrayList<String> jsonToObj(String s) {
                return new Gson().fromJson(s,
                        new TypeToken<ArrayList<String>>() {
                        }.getType());
            }

            @Override
            public void onFail(int i, Object o, Object o1) {
            }

            @Override
            public void onResponseError(int i, Object o, Object o1) {
            }

            @Override
            public void onStart(Object o) {
            }

            @Override
            public void onResponse(ResponseEntity<ArrayList<String>> responseEntity, Object o) {
                autoList.clear();
                autoList.addAll(responseEntity.getResponseElement());
                autoAdapter.notifyDataSetChanged();
            }
        });
    }

    public void saveInfo(List<SearchBean> datas) {
        JSONArray mJsonArray = new JSONArray();
        for (int i = 0; i < datas.size(); i++) {
            //SearchBean bean = datas.get(i);
            JSONObject object = new JSONObject();
            try {
                object.put("type", datas.get(i).getType());
                object.put("content", datas.get(i).getContent());
            } catch (JSONException e) {
            }
            mJsonArray.put(object);
        }
        SharedPreferences sp = this.getSharedPreferences("home_search_history", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("home_search_history_new", mJsonArray.toString());
        editor.commit();
        Log.e("home__history_save", mJsonArray.toString());
    }

    public ArrayList getHistory() {
        ArrayList datas = new ArrayList();
        SharedPreferences sp = this.getSharedPreferences("home_search_history", Context.MODE_PRIVATE);
        String result = sp.getString("home_search_history_new", "");
        Log.e("home_search_history", result.toString());

        try {
            JSONArray array = new JSONArray(result);
            for (int i = 0; i < array.length(); i++) {
                SearchBean bean = new SearchBean();
                JSONObject itemObject = array.getJSONObject(i);
                bean.setType(itemObject.getInt("type"));
                bean.setContent(itemObject.getString("content"));
                datas.add(bean);
            }
        } catch (JSONException e) {
        }
        return datas;
    }

    //************************************************************百度语音搜索*********************************************************************************

    private void initVoiceConfigure() {
        asr = EventManagerFactory.create(this, "asr");
        asr.registerListener(this);
    }

    /**
     * 按钮状态切换
     *
     * @param voiceCheck 是否可以录音 true：可以 false：不可以
     */
    private void updateButtonStatus(boolean voiceCheck) {
        if (voiceCheck) {
            txt_voice_search.setText("语音搜索");
            txt_voice_search.setTextColor(Color.parseColor("#24af75"));
            txt_voice_search.setBackgroundResource(R.drawable.btn_voice_search);
            Drawable drawable = SearchActivity.this.getResources().getDrawable(R.mipmap.icon_microphone_green);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            txt_voice_search.setCompoundDrawables(drawable, null, null, null);
            img_cancel.setVisibility(View.GONE);
            isVoiceRunning = false;
        } else {
            txt_voice_search.setText("结束录音");
            txt_voice_search.setTextColor(Color.parseColor("#ffffff"));
            txt_voice_search.setBackgroundResource(R.drawable.btn_voice_no_search);
            Drawable drawable = SearchActivity.this.getResources().getDrawable(R.mipmap.icon_microphone_white);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            txt_voice_search.setCompoundDrawables(drawable, null, null, null);
            img_cancel.setVisibility(View.VISIBLE);
            isVoiceRunning = true;
        }
    }

    /**
     * 基于SDK集成 发送开始事件
     * 点击开始按钮
     * 测试参数填在这里
     */
    private void voiceStart() {
        updateButtonStatus(false);

        //基于SDK集成,设置识别参数
        Map<String, Object> params = new LinkedHashMap<>();
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
        String json; // 可以替换成自己的json
        json = new JSONObject(params).toString(); // 这里可以替换成你需要测试的json
        asr.send(SpeechConstant.ASR_START, json, null, 0, 0);
    }

    /**
     * 点击停止按钮
     * 基于SDK集成 发送停止事件
     */
    private void voiceActiveStop() {
        updateButtonStatus(true);
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
    }

    private void voiceAutoStop(boolean haveResult) {
        if (!activeShutdown) {
            updateButtonStatus(true);
        }
        if (haveResult) {
            actionbar.setVisibility(View.VISIBLE);
            rl_tips.setVisibility(View.GONE);
        }
        activeShutdown = false;
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
    }

    /**
     * 点击取消按钮
     * 基于SDK集成 发送取消事件
     */
    private void voiceCancel() {
        updateButtonStatus(true);
        actionbar.setVisibility(View.VISIBLE);
        rl_tips.setVisibility(View.GONE);
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
    }

    @Override
    public void onEvent(String name, String params, byte[] bytes, int offset, int length) {
        Log.i("voice_flag:", name);
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_READY)) {
            //提示开始说话
            haveRecording = false;
            beginRecording();
        }

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_END)) {
            //说话结束提示开始识别
            beginIdentify();
        }

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_FINISH)) {
            if (!haveRecording) {
                showNoVoice();
            } else {
                showVoiceResult();
            }
        }
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {

            if (params != null) {
                VoiceResult voiceResult = VoiceResult.parseJson(params);
                // 识别结果
                String[] results = voiceResult.getResultsRecognition();
                if (voiceResult.isFinalResult()) {
                    // 最终识别结果，长语音每一句话会回调一次
                    haveRecording = true;
                    txt_tip1.setText(results[0]);
                }
            }

        }
    }


    private void beginRecording() {
        actionbar.setVisibility(View.GONE);
        rl_tips.setVisibility(View.VISIBLE);
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setText("你可以试试这样说");
        txt_tip1.setTextColor(Color.parseColor("#313131"));
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.VISIBLE);
        txt_tip4.setVisibility(View.VISIBLE);
        txt_tip5.setVisibility(View.VISIBLE);
        img_gif_voice.setVisibility(View.VISIBLE);
    }

    private void beginIdentify() {
        img_voice_identify.setVisibility(View.VISIBLE);
        txt_tip1.setVisibility(View.GONE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.GONE);
        txt_tip4.setVisibility(View.GONE);
        txt_tip5.setVisibility(View.GONE);
        img_gif_voice.setVisibility(View.GONE);
    }

    private void showVoiceResult() {
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setTextColor(Color.parseColor("#313131"));
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.GONE);
        txt_tip3.setVisibility(View.GONE);
        txt_tip4.setVisibility(View.GONE);
        txt_tip5.setVisibility(View.GONE);
        img_gif_voice.setVisibility(View.GONE);
        autoSearch(txt_tip1.getText().toString());
    }

    private void showNoVoice() {
        img_voice_identify.setVisibility(View.GONE);
        txt_tip1.setTextColor(Color.parseColor("#f13d1a"));
        txt_tip1.setText("未检测到语音");
        txt_tip1.setVisibility(View.VISIBLE);
        txt_tip2.setVisibility(View.VISIBLE);
        txt_tip3.setVisibility(View.VISIBLE);
        txt_tip4.setVisibility(View.VISIBLE);
        txt_tip5.setVisibility(View.VISIBLE);
        img_gif_voice.setVisibility(View.GONE);
        voiceAutoStop(false);
    }

    private void autoSearch(final String keyWord) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                voiceAutoStop(true);
                toSearch(keyWord);
            }
        }, 1000);

    }

    private void toSearch(String keyWord) {
        etContent.setText(keyWord);
        etContent.setSelection(keyWord.length());
        tvSearch.performClick();
    }

    private void audioPermissionCheck() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
        } else {
            voiceStart();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    voiceStart();
                } else {
                    T.toast("请到设置中打开应用语音权限！");
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        saveInfo(beanList);
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (img_gif_voice != null) {
            ((GifDrawable) img_gif_voice.getDrawable()).stop();
        }
        asr.send(SpeechConstant.ASR_CANCEL, null, null, 0, 0);
        asr.unregisterListener(this);
        super.onDestroy();
    }
}
